from Crypto.Cipher import AES
from Crypto.Util import Padding
import socket
import json
import binascii

HOST = '127.0.0.1'
PORT = 65432

# 打开图像文件并读取二进制数据
with open('1.png', 'rb') as f:
    image_data = f.read()
image_data_hex = binascii.hexlify(image_data).decode('utf-8')
# 定义加密密钥和初始向量
key = b'\r\xa3ki\t$\n\xab\n\xf7\xf0\xd5?\x9e\xccP'
iv = b'\x8d\x9a\xe7f\x18\xe2Z\xd2x\x11\x1e\x91\xc6\x89d\xb0'

def decode(hex_string):
    hex_string = hex_string.encode()
    encrypted_string = binascii.unhexlify(hex_string)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_string = cipher.decrypt(encrypted_string)
    string = Padding.unpad(padded_string, AES.block_size, style='pkcs7')
    return string.decode()

# Function to decrypt the received content
def decrypt_response(response_encrypted):
    encrypted_string = binascii.unhexlify(response_encrypted)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_string = cipher.decrypt(encrypted_string)
    string = Padding.unpad(padded_string, AES.block_size, style='pkcs7')
    return string.decode()

# 创建AES加密模块
cipher = AES.new(key, AES.MODE_CBC, iv)
# 构造JSON数据
student = {
    'name': 'John',   
    'id': 123,
    'image': image_data_hex
}

student_json = json.dumps(student)
# 对JSON字符串进行填充并加密 
student_padded = Padding.pad(student_json.encode(), AES.block_size,style='pkcs7')
student_encrypted = cipher.encrypt(student_padded)

# 发送密文到服务器
with socket.socket() as s:
    s.connect((HOST, PORT))  
    s.sendall(student_encrypted)
    s.shutdown(socket.SHUT_WR)
    
    response_encrypted = s.recv(1024)
    # 解密服务器返回的消息
    print(decrypt_response(response_encrypted))